var Log = {
	elem: false,
	write: function(text){
		if (!this.elem)
			this.elem = document.getElementById('log');
		this.elem.innerHTML = text;
		this.elem.style.left = (500 - this.elem.offsetWidth / 2) + 'px';
	}
};

function addEvent(obj, type, fn) {
	if (obj.addEventListener) obj.addEventListener(type, fn, false);
	else obj.attachEvent('on' + type, fn);
}


function init(){

	var infovis = document.getElementById('infovis');
	var w = infovis.offsetWidth , h = infovis.offsetWidth ;
	//Create a new canvas instance.
	var canvas = new Canvas('mycanvas', {
		'injectInto':'infovis',
		'width': w,
		'height':h,
		'styles': {
			'fillStyle': '#1667DA',
			'strokeStyle': '#A4A4A4'
		},
		'backgroundCanvas': {
			'styles': {
				'fillStyle': '#1667DA',
				'strokeStyle': '#A4A4A4'
			},

			'impl': {
				'init': function() { },
				'plot': function(canvas, ctx) {
					var pi2 = Math.PI*2;
					ctx.beginPath();
					ctx.arc(0, 0,  ((w < h)? w : h) / 2, 0, pi2, true);
					ctx.stroke();
					ctx.closePath();
				}
			}

		}
	});

	//init Hypertree
	var ht = new Hypertree(canvas, {
		clickedNodeId: "",
		clickedNodeName: "",
		/*
        Node: {
            dim: 9,
            color: "#f00"
        },
		*/
	   /*
        Edge: {
            lineWidth: 12,
            color: "#088"
        },
		*/
		onBeforeCompute: function(node){
			Log.write("centering");
		},
		//Add the node's name to its corresponding label.
		//This method is only called on label creation.
		onCreateLabel: function(domElement, node){
			domElement.innerHTML = node.name;
			addEvent(domElement, 'click', function () {
				ajaxWrapper(node.id);
				ht.onClick(node.id);
			});
		},

		//Ths method is called when moving/placing a label.
		//Add label styles based on their position.
		onPlaceLabel: function(domElement, node){
			var style = domElement.style;
			style.display = '';
			if (node._depth <= 1) {
				style.fontSize = "0.8em";
			//style.color = "#ddd";

			} else if(node._depth == 2){
				style.fontSize = "0.7em";
				style.color = "#555";

			} else {
				style.display = 'none';
			}

			var left = parseInt(style.left);
			var w = domElement.offsetWidth;
			style.left = (left - w / 2) + 'px';
		},

		onAfterCompute: function(){
			Log.write("done");
			var node = Graph.Util.getClosestNodeToOrigin(ht.graph, "pos");
			this.clickedNodeId = node.id;
			this.clickedNodeName = node.name;
			this.requestGraph();
		},

		preprocessTree: function(json) {
			var ch = json.children;
			var getNode = function(nodeName) {
				for(var i=0; i<ch.length; i++) {
					if(ch[i].name == nodeName) return ch[i];
				}
				return false;
			};
			json.id = this.clickedNodeId;
			
			Graph.Util.eachAdjacency(ht.graph.getNode(this.clickedNodeId), function(elem) {
				var nodeTo = elem.nodeTo, jsonNode = getNode(nodeTo.name);
				if(jsonNode) jsonNode.id = nodeTo.id;
			});
			
		},

		requestGraph: function() {
			var that = this, id = this.clickedNodeId;
			Log.write("requesting info...");
			jQuery.getJSON(
				'json/jsonData.jsf', null,
				function(json) {
					Log.write("morphing...");
					that.preprocessTree(json);
					ht.op.morph(json, {
						'id': id,
						'type': 'fade',
						'duration':1000,
						hideLabels:true,

						onComplete: function() {
							Log.write("done");
						},

						onAfterCompute: function(){},
						onBeforeCompute: function(){}
					});
				});

		}
	});

	//load JSON data.
	/*
	ht.loadJSON(json);

	//Add some edges to transform the
	//tree into a graph (just for fun).
	ht.graph.addAdjacence({
		'id': '236585_30'
	}, {
		'id': '236583_23'
	}, null);
	ht.graph.addAdjacence({
		'id': '236585_30'
	}, {
		'id': '4619_46'
	}, null);

	//Compute positions and plot.
	ht.refresh();
	//end
	*/
	//Global Options
	//Define a function that returns the selected duration
	function getDuration() {
		return 1000;
	}
	//Define a function that returns the selected fps
	function getFPS() {
		return 30;
	}
	//Define a function that returns whether you have to
	//hide labels during the animation or not.
	function hideLabels() {
		return false;
	}

	//init handlers
	//Add event handlers to the right column controls.

	//Morph
	function cl_morph(){
		//get graph to morph to.
		var trueGraph = eval('(' + graph + ')');
		//get animation type.
		var stype = document.getElementById('select-type-morph');
		var sindex = stype.selectedIndex;
		var type = stype.options[sindex].text;
		//perform morphing animation.
		ht.op.morph(trueGraph, {
			type: type,
			fps: getFPS(),
			duration: getDuration(),
			hideLabels: hideLabels(),
			onComplete: function(){
				Log.write("morph complete!");
			}
		});
	};
	PageController.ht = ht;
	PageController.canvas = canvas;
//end
}

var PageController = {
	ht: null,
	busy:false,
	canvas:null,

	makeRequestAndPlot: function(name) {

		if(this.busy) return;
		this.busy = true;
		var that = this;
		if(this.ht.busy == true) return;
		//Animation.timer = clearInterval(Animation.timer);
		this.ht.busy = false;
		//name = encodeURIComponent(name);
		var ht = this.ht;
		ht.controller.clickedNodeId = "";
		ht.controller.clickedNodeName = "";

		Log.write("wait for it... it might take a while");
		jQuery.getJSON(
			'json/jsonData.jsf', null,
			function(json) {
				//				GraphPlot.labelsHidden = false;
				//				GraphPlot.labels = {};
				//jQuery('#mycanvas-label').css('display', '');
				//load weighted graph.
				ht.loadJSON(json,0);
				//compute positions
				ht.compute();
				//make first plot
				ht.plot();
				//ht.controller.clickedNodeName = name;
				that.busy = false;
				Log.write("done");
			});
	}

};

function init_graph(){
	//Layout.init();
	init();
	PageController.makeRequestAndPlot('node0');
}

